package com.com.gmail.at.vssabinin.adminclient;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JDialog;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import DTO.PassengerDTO;

import javax.swing.ListSelectionModel;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;

public class PassengerManager extends javax.swing.JDialog  implements TableModelListener {

	private static final long serialVersionUID = 1L;
	
	private SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");

	
	public static PassengerManager passengerInstance = new PassengerManager(Main.mainInstance, true);

	private HashSet<PassengerDTO> modifiedPassengers = new HashSet<PassengerDTO>();
    private HashSet<PassengerDTO> removedPassengers = new HashSet<PassengerDTO>();
    
    private boolean changes = false;
    
	private DefaultTableModel tableModel = new DefaultTableModel(null, new String [] 
	    		{"PassengerID", "Name", "Surname", "Date of birth", "Login", "Password"});
	
    public PassengerManager(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        setResizable(false);
        initComponents();
    }

    public void update() {
    	if (this.tableModel.getRowCount() > 0) {
    	    for (int i = this.tableModel.getRowCount() -1; i > -1; i--) {
    	    	((DefaultTableModel) this.tableModel).removeRow(i);
    	    }
    	}
    	Main.mainInstance.client.sendThroughProtocol("adminManagePassengersDat", null);
        Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
        if (message.getType().equals("ok")) {
        	@SuppressWarnings("unchecked")
			List<PassengerDTO> passengers = (List<PassengerDTO>) message.getObject();
        	for (int i = 0; i < passengers.size(); i++) {
            	String[] row = {"" + passengers.get(i).getPassengerID(), passengers.get(i).getPassengerName(), 
            			passengers.get(i).getPassengerSurname(), passengers.get(i).getPassengerDateOfBirth().toString(), 
            			passengers.get(i).getLogin(), passengers.get(i).getPassword()};
            	((DefaultTableModel) this.tableModel).addRow(row);
            }
        }
        this.tableModel.fireTableDataChanged();
    }
    private void initComponents() {

        refresh = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        passengersTable = new javax.swing.JTable();
        passengersTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        delete = new javax.swing.JButton();
        goBack = new javax.swing.JButton();
        save = new javax.swing.JButton();

        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

        refresh.setText("refresh the table");

        jScrollPane1.setViewportView(passengersTable);

        delete.setText("delete selected passenger(row)");
        delete.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                deleteMouseReleased(evt);
            }
        });
        
        passengersTable.setModel(tableModel);
        tableModel.addTableModelListener(this);

        goBack.setText("go back to the main menu");

        save.setText("save changes");
        
        save.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                saveMouseReleased(evt);
            }
        });

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        
        goBack.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                goBackMouseReleased(evt);
            }
        });

        refresh.setText("refresh table");
        refresh.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                refreshMouseReleased(evt);
            }
        });
        

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 946, Short.MAX_VALUE)
        				.addGroup(layout.createSequentialGroup()
        					.addComponent(goBack)
        					.addGap(229)
        					.addComponent(delete)
        					.addPreferredGap(ComponentPlacement.RELATED, 278, Short.MAX_VALUE)
        					.addComponent(save))
        				.addGroup(layout.createSequentialGroup()
        					.addGap(394)
        					.addComponent(refresh, GroupLayout.PREFERRED_SIZE, 140, GroupLayout.PREFERRED_SIZE)))
        			.addContainerGap())
        );
        layout.setVerticalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addComponent(refresh)
        			.addPreferredGap(ComponentPlacement.UNRELATED)
        			.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 425, GroupLayout.PREFERRED_SIZE)
        			.addGap(18)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(save)
        				.addComponent(goBack)
        				.addComponent(delete))
        			.addContainerGap(13, Short.MAX_VALUE))
        );
        getContentPane().setLayout(layout);

        pack();
    }
    public static void main(String args[]) {
       
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PassengerManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PassengerManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PassengerManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PassengerManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
  
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PassengerManager dialog = new PassengerManager(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    private void refreshMouseReleased(java.awt.event.MouseEvent evt) {
    	this.update();
    }
    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {
        this.update();
    }
    
    private void goBackMouseReleased(java.awt.event.MouseEvent evt) {
    	if (changes) {
    		int selection = JOptionPane.showConfirmDialog(null, "Do you want to save changes?", "Information", 
        			JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
        	if (selection == JOptionPane.YES_OPTION) {
        		this.saveMouseReleased(evt);
        	}
    	}
    	Main.mainInstance.loginViewSet();
        this.dispose();
    }
    
    private void deleteMouseReleased(java.awt.event.MouseEvent evt) {
    	PassengerDTO passenger= new PassengerDTO();
    	int id = this.passengersTable.getSelectedRow();
    	if (id != -1) { 
    		int selection = JOptionPane.showConfirmDialog(null, "This will delete the passenger, and all the tickets," +
    				" that are associated with him!", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
        	if (selection == JOptionPane.YES_OPTION) {
        		passenger.setPassengerID(Integer.valueOf((String)this.tableModel.getValueAt(id, 0)));
            	((DefaultTableModel) this.tableModel).removeRow(id);
            	this.removedPassengers.add(passenger);
            	this.tableModel.fireTableDataChanged();
            	this.changes = true;
        	}
    	}
    }
    
    private void saveMouseReleased(java.awt.event.MouseEvent evt) {
    	if (!this.modifiedPassengers.isEmpty()) {
    		Main.mainInstance.client.sendThroughProtocol("adminModifyPassengers", this.modifiedPassengers);
        	Protocol.Message message1 = Main.mainInstance.client.readThroughProtocol();
        	if (message1.getType().equals("ok")) {
        		this.modifiedPassengers.clear();	
        	}
        }
        if (!this.removedPassengers.isEmpty()) {
        	Main.mainInstance.client.sendThroughProtocol("adminRemovePassengers", this.removedPassengers);
        	Protocol.Message message1 = Main.mainInstance.client.readThroughProtocol();
        	if (message1.getType().equals("ok")) {
        		this.removedPassengers.clear();	
        	}
		}
        this.update();
        this.changes = false;
        JOptionPane.showMessageDialog(null, "You have successfully made ​​changes!"); 
    }
    
    private javax.swing.JButton delete;
    private javax.swing.JButton goBack;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable passengersTable;
    private javax.swing.JButton refresh;
    private javax.swing.JButton save;
    
    public void tableChanged(TableModelEvent e) {
		int row = e.getFirstRow();
		int column = e.getColumn();
		if (row >= 0  && column >= 0) {
			DefaultTableModel model = (DefaultTableModel)e.getSource();
		    Object data = model.getValueAt(row, column);
		    PassengerDTO passenger = new PassengerDTO();
		    Date dateOfBirth = null;
			try {
				dateOfBirth = dataFormat.parse((String) this.tableModel.getValueAt(row, 3));
			} catch (ParseException e1) {
				JOptionPane.showMessageDialog(null, "Internal error, try once more!");
				this.update();
			}
			passenger.setPassengerID(Integer.valueOf((String)this.tableModel.getValueAt(row, 0)));
			passenger.setPassengerName((String)this.tableModel.getValueAt(row, 1));
			passenger.setPassengerSurname((String)this.tableModel.getValueAt(row, 2));
			passenger.setPassengerDateOfBirth(dateOfBirth);
			passenger.setLogin((String)this.tableModel.getValueAt(row, 4));
			passenger.setPassword((String)this.tableModel.getValueAt(row, 5));
		    switch (column) {
		    	case 0: break;
		    	case 1:	passenger.setPassengerName((String) data);
		    			break;
		    	case 2: passenger.setPassengerSurname((String) data);
						break;
		    	case 3:	try {
							dateOfBirth = dataFormat.parse((String) data);
						} catch (ParseException e1) {
							JOptionPane.showMessageDialog(null, "Error in date of birth! Check it!");
						}	
		    			passenger.setPassengerDateOfBirth(dateOfBirth);
						break;
		    	case 4: passenger.setLogin((String) data);
						break;
		    	case 5: passenger.setPassword((String) data);
						break;
		    }
		    this.modifiedPassengers.add(passenger);
		    this.changes = true;
		    this.tableModel.fireTableDataChanged();
		}
	}
}
